﻿using System;
using Reactor.Environment;

namespace Reactor.Messaging.ServiceBus.Delivery
{
    /// <summary>
    /// Responsible for finding proper message handler types for the message being delivered, creating instances, and 
    /// delivering the messages by passing them as parameters to the Handle method of each message handler.
    /// </summary>
    public class DeliveryCoordinator
    {
        /// <summary>
        /// Delivers the message to new instances of all message handler types suitable for handling such a message.
        /// </summary>
        /// <param name="message">The message to be delivered.</param>
        /// <param name="messageContext">The message context.</param>
        /// <exception cref="ArgumentNullException">Throws if <paramref name="message"/> or <paramref name="messageContext"/> parameters are null.</exception>
        /// <exception cref="InvalidOperationException">Throws if there is no IServiceBus instance found at Context.ServiceBus. Will also throw 
        /// if an instance is found, but doesnt have a <seealso cref="BusConfiguration"/> element or <seealso cref="IDestinationRegistry"/> configured.</exception>
        public void DeliverMessage(object message, IMessageContext messageContext)
        {
            if (message == null) throw new ArgumentNullException("message");
            if (messageContext == null) throw new ArgumentNullException("messageContext");
            if (Context.ServiceBus == null) throw new InvalidOperationException("No IServiceBus instance found at Context.ServiceBus.");
            if (Context.ServiceBus.Configuration == null) throw new InvalidOperationException("IServiceBus instance found at Context.ServiceBus has no BusConfiguration instance.");
            if (Context.ServiceBus.Configuration.DestinationRegistry == null) throw new InvalidOperationException("IServiceBus instance found at Context.ServiceBus has no IDestinationRegistry instance configured.");

            //Obtain list of types that handle this message
            var handlerTypes = Context.ServiceBus.Configuration.MessageHandlerRegistry.GetHandlerTypesForMessageType(message.GetType());

            foreach (var handlerType in handlerTypes)
            {
                var handler = Activator.CreateInstance(handlerType);
                var handleMethod = handlerType.GetMethod("Handle");

                handleMethod.Invoke(handler, new[] { message, messageContext });
            }
        }
    }
}
